Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Amazon Hard Problems
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Count Array Pairs Divisible by K

Problem Statement

Given an integer array nums containing n elements and an integer k, return the number of pairs (i, j) such that 0 <= i < j <= n - 1 and nums[i] * nums[j] is divisible by k.

Examples

  • Example 1:

    • Input: nums = [8, 4, 6, 12], k = 4
    • Expected Output: 6
    • Justification: The pairs that satisfy the conditions are (8, 4), (8, 6), (8, 12), (4, 6), (4, 12), and (6, 12). The products of these pairs are divisible by 4.
  • Example 2:

    • Input: nums = [10, 5, 2, 6], k = 5
    • Expected Output: 5
    • Justification: The valid pairs are (10, 5), (10, 2), (5, 2), (5, 6), and (10, 6). Each product of these pairs is divisible by 5.
  • Example 3:

    • Input: nums = [4, 7, 9, 11, 23], k = 3
    • Expected Output: 4
    • Justification: The pairs are (4, 9), (7, 9), (9, 11), and (9, 23). The products of these pairs are divisible by 3.

Solution

To solve this problem, we adopt a mathematical and hash map-based approach that focuses on the properties of divisibility and the Greatest Common Divisor (GCD). The core idea hinges on the fact that if the product of two numbers is divisible by k, then the GCD of each number with k must also meet certain divisibility conditions.

Specifically, for two numbers a and b, if gcd(a, k) * gcd(b, k) is divisible by k, then a * b is divisible by k. This insight allows us to transform the problem into one of counting pairs based on their GCDs with k, significantly reducing the problem's complexity from potentially quadratic to more manageable levels. We leverage a hash map to efficiently count and pair up elements with compatible GCDs, ensuring a thorough yet efficient examination of all possible pairings without direct multiplication, thus optimizing both performance and scalability.

Step-by-Step Algorithm

  1. Initialize a result variable: This variable will hold the final count of pairs whose product is divisible by k.

  2. Create a hash map (gcdMap): This map will store the greatest common divisor (GCD) of the elements in the array with k as keys, and the frequency of these GCDs as values.

  3. Iterate through the array:

    • For each element in the array, calculate the GCD of the element and k.
    • For every GCD value calculated, iterate through the keys in gcdMap:
      • If the product of the current GCD and any GCD in the map is divisible by k (checking (long) gcd * num % k == 0 to avoid integer overflow), add the frequency of that GCD in the map to the result. This step effectively counts pairs formed by the current element and elements previously processed.
    • Update gcdMap with the current GCD, incrementing its frequency by 1. If the GCD is already a key in the map, its value is increased; otherwise, it is added to the map with a frequency of 1.
  4. Return the result: After iterating through all elements in the array and updating the result based on the conditions checked, return the final count of pairs.

Algorithm Walkthrough

Let's consider the Input: nums= [10, 5, 2, 6], k = 5.

  1. Initialization: Start with an empty gcdMap and result set to 0.

  2. First element (10):

    • Compute gcd(10, 5) = 5.
    • No existing keys in gcdMap, so nothing to add to the result yet. result = 0.
    • Update gcdMap to {5: 1}.
  3. Second element (5):

    • Compute gcd(5, 5) = 5.
    • Existing key 5 in gcdMap with frequency 1. Since 5 * 5 % 5 == 0, add 1 to the result. result = 1.
    • Update gcdMap to {5: 2} (since 5 appears twice now).
  4. Third element (2):

    • Compute gcd(2, 5) = 1.
    • For existing key 5 in gcdMap: 5 * 1 % 5 == 0, add 2 to the result (because there are 2 elements with GCD 5 so far). result = 3.
    • Update gcdMap to {5: 2, 1: 1}.
  5. Fourth element (6):

    • Compute gcd(6, 5) = 1.
    • For existing key 5 in gcdMap: 5 * 1 % 5 == 0, add 2 to the result. result = 5.
    • For existing key 1 in gcdMap: 1 * 1 % 5 == 4. So, don't need to add anything in result.
    • Update gcdMap to {5: 2, 1: 2}.
  6. Final result: The total count of valid pairs is 5.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: , where n is the number of elements in the input array, log(k) is the complexity of calculating the GCD of an element with k, and D(k) represents the number of distinct divisors of k. This accounts for iterating through each element, calculating the GCD, and checking divisibility conditions with all entries in a map.

  • Space Complexity: , which is determined by the number of distinct GCD values stored in the map, corresponding to the number of distinct divisors of k. This space is used to track the frequency of each GCD value among the elements of the array.

Count Array Pairs Divisible by K (hard)
Word Ladder (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis